<style rel="stylesheet/scss" lang="scss" scoped>
@import "../../../styles/prod.scss";

.upload-df {
  vertical-align: top;
  margin-right: 10px;
}

.upload-img {
  padding: 0;
}
</style>
<template>
  <!-- 产品档案 -->
  <div class="app-container calendar-list-container">
    <div class="pds-tip-green">
      <p>
        <el-select v-model="search.importType" placeholder="请选择">
          <el-option v-for="item in [{label:'机型号',value:2},{label:'报价单',value:1}]" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <el-input style="width: 200px;" class="filter-item" placeholder="请输入" v-model="search.context">
        </el-input>
        <el-button class="filter-item" type="success" icon="search" @click="importModel()" size="small">导入</el-button>
      </p>
    </div>
    <!-- 基本属性 -->
    <custom-card title="基本信息" class="mt-30">
      <template>
        <basic-form :basicInfo="basicForm" :ruleForm="detail.pdsFileModelBaseDto" ref="basicForm" :lang="language"></basic-form>
      </template>
    </custom-card>
    <!-- 销售区域 -->
    <custom-card title="销售区域/国家" class="mt-30">
      <template>
        <el-form label-width="140px" class="mt-20">
          <el-form-item label="请选择：">
            <el-checkbox-group v-model="detail.pdsFileModelSaleAreasArray">
              <el-checkbox border v-for="option in countryList" :key="option.id" :label="option.value">
                {{language=='en'?option.labelEnUs:option.labelZhCh}}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="备注：">
            <el-input type="textarea" placeholder="请输入内容" style="width:60%" v-model="detail.pdsFileModelBaseDto.salesAreaRemark"></el-input>
          </el-form-item>
        </el-form>
      </template>
    </custom-card>
    <prod-file ref="prodfile" page="articleModel"></prod-file>
    <!-- 产品颜色 -->
    <custom-card title="颜色部件" class="mt-30">
      <el-row class="">
        <el-col :span="6">
          <el-input placeholder="输入关键字进行过滤" v-model="detail.color">
          </el-input>
          <el-tree class="filter-tree" :data="colorTreeList" default-expand-all @node-click="handleColorClick" :filter-node-method="filterColor" ref="treeColor">
          </el-tree>
        </el-col>
        <el-col :span="18" style="padding-left:20px">
          <el-table :data="detail.showColorsList" border style="width: 100%">
            <el-table-column label="序号" min-width="15%" type="index">
              <template slot-scope="scope">
                {{scope.$index+1}}
              </template>
            </el-table-column>
            <el-table-column label="部件" min-width="35%">
              <template slot-scope="scope">
                {{language=='en'?scope.row.nameEn:scope.row.nameCn}}
              </template>
            </el-table-column>
            <el-table-column label="颜色" min-width="15%">
              <template slot-scope="scope">
                <el-input type="" v-model="scope.row.color"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="色值" min-width="15%">
              <template slot-scope="scope">
                <el-input type="" v-model="scope.row.colorValue"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="20%">
              <template slot-scope="scope">
                <el-button class="filter-item" type="danger" size="mini" @click="deletItem(scope.row.$index,detail.showColorsList)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </custom-card>
    <custom-card title="客户管控点" class="mt-30">
      <template>
        <el-form label-width="140px" class="mt-20">
          <el-form-item label="管控点说明:">
            <el-input type="textarea" placeholder="请输入内容" style="width:60%" v-model="detail.pdsFileModelBaseDto.customerControlPoint"></el-input>
          </el-form-item>
        </el-form>
      </template>
    </custom-card>
    <div class="pds-btm mt-30">
      <div v-if="articlePcsId && detail.pdsFileModelBaseDto.status == 0">
        已保存草稿
        <span class="tip">{{detail.pdsFileModelBaseDto.updateTime | formatTime}}</span>
      </div>
      <div class="right">
        <el-button class="filter-item" type="warning" @click="submitForm('draft')" :loading="loading">保存草稿</el-button>
        <el-button class="filter-item" type="primary" @click="submitForm('save')" :loading="loading">提交</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import { mapGetters } from 'vuex';
import BasicForm from '@/components/BasicForm/index';
import * as baseApi from '@/api/common/index';
import * as addApi from '@/api/sale/model/index';
import * as prodApi from '@/api/product/index';
import ProdFile from '@/components/Product/prodFile';

export default {
  name: 'user',
  components: {
    BasicForm,
    ProdFile
  },
  data() {
    return {
      loading: false,
      countryList: [],
      colorTreeList: [],
      articlePcsId: null,
      detail: {},
      search: {
        context: '',
        importType: ''
      },
      basicForm: [
        {
          label: 'sale.model.customer',
          unit: '',
          element: 'selectFilter',
          name: 'customerId',
          type: 'filter',
          isRequired: true
        },
        {
          label: 'sale.model.customerModel',
          unit: '',
          element: 'input',
          name: 'customerModel',
          type: '',
          isRequired: true
        },
        {
          label: 'sale.model.plmArticleNo',
          unit: '',
          element: 'input',
          name: 'plmArticleNo',
          type: '',
          isRequired: true
        },
        {
          label: 'sale.model.plmModelNo',
          unit: '',
          element: 'input',
          name: 'plmModelNo',
          type: '',
          isRequired: true,
          disabled: true
        },
        {
          label: 'sale.model.brandName',
          unit: '',
          element: 'input',
          name: 'brandName',
          type: '',
          isRequired: true
        },
        {
          label: 'sale.model.name',
          unit: '',
          name: 'name',
          element: 'input',
          type: '',
          isRequired: false,
          options: []
        },
        {
          label: 'sale.model.pdsConfCertCategory',
          unit: '',
          element: 'select',
          name: 'pdsConfCertCategoryArray',
          type: 'multiple',
          options: [],
          isRequired: true
        },
        {
          label: 'sale.model.plugType',
          unit: '',
          element: 'select',
          name: 'plugTypeDv',
          dictCode: 'prod_file_plug_type',
          append: '',
          type: '',
          isRequired: true
        },
        {
          label: 'sale.model.powerCableMaterial',
          unit: '',
          element: 'input',
          name: 'powerCableMaterial',
          type: '',
          isRequired: false
        },
        {
          label: 'sale.model.powerCableLength',
          unit: '',
          element: 'input',
          name: 'powerCableLength',
          append: 'cm',
          type: 'number',
          isRequired: true
        },
        {
          label: 'sale.model.latestSellingPrice',
          unit: '',
          element: 'input',
          name: 'latestSellingPrice',
          // type: 'number',
          append: '元',
          isRequired: true,
          limitNum: 3
        },
        {
          label: 'sale.model.environmentalProtectionGrade',
          unit: '',
          element: 'select',
          name: 'environmentalProtectionGrade',
          append: '元',
          isRequired: true,
          limitNum: 3,
          options: [
            {
              id: 1,
              value: 1,
              labelZhCh: '无要求'
            },
            {
              id: 2,
              value: 2,
              labelZhCh: 'ROHS（R）'
            },
            {
              id: 3,
              value: 3,
              labelZhCh: 'PAHS（PR）'
            },
            {
              id: 4,
              value: 4,
              labelZhCh: 'REACH（PPR）'
            },
            {
              id: 5,
              value: 5,
              labelZhCh: '加州（65）'
            },
            {
              id: 6,
              value: 6,
              labelZhCh: 'ALDI 要求'
            }
          ]
        },
        {
          label: 'sale.model.isAntiUv',
          unit: '',
          element: 'radio',
          append: '',
          name: 'isAntiUv',
          type: '',
          options: [
            {
              labelZhCh: '是',
              labelEnUs: 'Y',
              value: 1,
              id: 1
            },
            {
              labelZhCh: '否',
              labelEnUs: 'N',
              value: 0,
              id: 0
            }
          ],
          defaultValue: 0,
          isRequired: true
        },
        {
          label: 'sale.model.timeRequirement',
          element: 'input',
          type: 'number',
          append: '小时',
          name: 'timeRequirement',
          hidden: true
        },
        {
          label: 'sale.model.detailRequirements',
          element: 'input',
          type: '',
          name: 'detailRequirements',
          hidden: true
        },
        {
          label: 'sale.model.barcodeType',
          unit: '',
          element: 'radio',
          append: '',
          name: 'barcodeType',
          type: '',
          col: 100,
          options: [
            {
              labelEnUs: 'UPC',
              labelZhCh: 'UPC',
              value: 1
            },
            {
              labelEnUs: 'EAN',
              labelZhCh: 'EAN',
              value: 2
            },
            {
              labelEnUs: 'other',
              labelZhCh: '不用我司',
              value: 3
            }
          ],
          defaultValue: 3,
          isRequired: true
        },
        {
          label: 'barcode',
          element: 'input',
          name: 'barcode',
          hidden: true
        },
        {
          label: 'sale.model.isUnderwriting',
          unit: '',
          element: 'radio',
          type: '',
          name: 'isUnderwriting',
          defaultValue: 0,
          options: [
            {
              labelZhCh: '是',
              labelEnUs: 'Y',
              value: 1,
              id: 1
            },
            {
              labelZhCh: '否',
              labelEnUs: 'N',
              value: 0,
              id: 0
            }
          ],
          col: 100,
          isRequired: true
        },
        {
          label: 'sale.model.underwritingWay',
          unit: '',
          element: 'radio',
          type: '',
          name: 'underwritingWay',
          hidden: true,
          options: [
            {
              labelZhCh: '整机',
              labelEnUs: 'Y',
              value: 1,
              id: 1
            },
            {
              labelZhCh: '部件',
              labelEnUs: 'N',
              value: 2,
              id: 2
            },
            {
              labelZhCh: '技术',
              labelEnUs: 'N',
              value: 3,
              id: 3
            }
          ],
          col: 100,
          defaultValue: 1,
          isRequired: true
        },
        {
          label: 'sale.model.underwritingMarket',
          unit: '',
          element: 'input',
          name: 'underwritingMarket',
          type: '',
          hidden: true,
          isRequired: true
        },
        {
          label: 'sale.model.underwritingCountry',
          unit: '',
          element: 'input',
          name: 'underwritingCountry',
          type: '',
          hidden: true,
          isRequired: true
        },
        {
          label: 'sale.model.FileModelPbsPics',
          unit: '',
          element: 'upload',
          name: 'pdsFileModelPbsPicsList',
          type: '',
          isRequired: false
        }
      ],
      productCategory: []
    };
  },
  created() {
    this.dataInit();
    this.getDict();
    this.getCertSelect();
  },
  activated() {},
  watch: {
    'detail.color'(val) {
      this.$refs.treeColor.filter(val);
    }
  },
  computed: {
    ...mapGetters(['elements', 'language'])
  },
  methods: {
    refresh() {
      if (this.$route.query.plmModelNoMain) {
        if (this.$route.query.plmModelNoMain != this.search.plmModelNoMain) {
          this.search.plmModelNoMain =
            this.$route.query.plmModelNoMain || this.search.plmModelNoMain;
          this.search.context = this.search.plmModelNoMain;
          this.importModel();
          this.clearValidate();
          return;
        }
      }
      if (this.$route.query.articlePcsId) {
        this.articlePcsId = this.$route.query.articlePcsId;
        this.getModelDetail();
        this.clearValidate();
        return;
      }
      this.dataInit();
      this.clearValidate();
    },
    dataInit() {
      const data = {
        pdsFileModelBaseDto: {
          pdsFileModelPbsPicsList: [],
          pdsConfCertCategoryArray: []
        },
        pdsFileModelSaleAreasArray: [],
        showColorsList: [],
        pdsConfCategoryArray: []
      };
      this.detail = JSON.parse(JSON.stringify(data));
      setTimeout(() => {
        this.$refs.prodfile.dataInit();
      });
    },
    clearValidate() {
      setTimeout(() => {
        this.$refs.basicForm &&
          this.$refs.basicForm.$refs.ruleForm.clearValidate();
      });
    },
    // 接口获取数据后更新
    refreshDetailCb(res) {
      if (res.code === 200) {
        if (
          res.data.pdsConfCategoryArray &&
          res.data.pdsConfCategoryArray.length == 3
        ) {
          this.getPdsConfColorTree(res.data.pdsConfCategoryArray[2]);
        }
        // res.data.showModules[0].paramsList[0].paramRequired=1
        res.data.pdsFileModelBaseDto.pdsFileModelPbsPicsList =
          res.data.pdsFileModelPbsPicsList;
        res.data.pdsFileModelBaseDto.pdsConfCertCategoryArray = res.data.pdsConfCertCategoryArray.map(
          value => Number(value)
        );
        this.$set(this, 'detail', res.data);
        res.data.showColorsList = res.data.showColorsList || [];
        // 客户回显处理
        if (res.data.pdsFileModelBaseDto.customerId) {
          this.$refs.basicForm.getPdsCustomerByName(
            res.data.pdsFileModelBaseDto.customerName
          );
        }
        // Barcode类型回显处理
        this.$refs.basicForm.radioChange(
          'barcodeType',
          null,
          res.data.pdsFileModelBaseDto.barcodeType
        );
        // 是否包销回显处理,如果是否的情况需要特殊处理，数据不双向绑定
        this.$refs.basicForm.radioChange(
          'isUnderwriting',
          null,
          res.data.pdsFileModelBaseDto.isUnderwriting
        );
        // 是否抗Uv
        this.$refs.basicForm.radioChange(
          'isAntiUv',
          null,
          res.data.pdsFileModelBaseDto.isAntiUv
        );
        this.$refs.prodfile.refresh(this.detail);
      } else {
        this.$message.error(res.message);
      }
    },
    // 新增型号档案导入
    importModel() {
      if (this.search.context) {
        addApi.importModel(this.search).then(res => {
          this.detail.showColorsList = [];
          this.refreshDetailCb(res);
        });
      }
    },
    // 修改档案获取详情
    getModelDetail() {
      addApi
        .modelDetail({
          articlePcsId: this.articlePcsId
        })
        .then(res => {
          this.refreshDetailCb(res);
        });
    },
    // 提交或草稿
    async submitForm(type) {
      const basicFormCheck = await this.$refs.basicForm.submitForm();
      const moduleFormRes = await this.$refs.prodfile.submitForm();
      if (!this.detail.pdsConfCategoryArray.length) {
        this.$message.error('请导入型号档案');
        return;
      }
      if (!basicFormCheck) {
        this.$message.error('请填写完整基本信息');
        return;
      }
      if (type === 'save') {
        // 提交
        this.detail.operation = 'submit';
        this.detail.status = 1;
        if (!this.detail.pdsFileModelSaleAreasArray.length) {
          this.$message.error('请选择销售国家');
        }
        if (!moduleFormRes.isValid) {
          this.$message.error('请填写完整模组信息');
          return;
        }
        if (!moduleFormRes.data.showFeaturesList.length) {
          this.$message.error('请选择产品特征');
          return;
        }
      } else {
        // 草稿
        this.detail.operation = 'save';
        this.detail.status = 0;
      }
      this.detail.showAccessoriesList = moduleFormRes.data.showAccessoriesList;
      this.detail.showFeaturesList = moduleFormRes.data.showFeaturesList;
      this.detail.showModules = moduleFormRes.data.showModules;
      this.saveToServer(type);
    },
    saveToServer(type) {
      if (this.loading) return;
      this.loading = true;
      const updataParams = JSON.parse(JSON.stringify(this.detail));
      updataParams.pdsFileModelPbsPicsList =
        updataParams.pdsFileModelBaseDto.pdsFileModelPbsPicsList;
      updataParams.pdsConfCertCategoryArray =
        updataParams.pdsFileModelBaseDto.pdsConfCertCategoryArray;
      const setModuleData = () => {
        updataParams.showModules.map(moduleItem => {
          if (moduleItem.paramsList && moduleItem.paramsList.length) {
            moduleItem.paramsList.map(paramsItem => {
              paramsItem.paramValue = moduleItem.formData[paramsItem.id];
            });
          }
        });
      };
      setModuleData();
      addApi.save(updataParams).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.$message.info('保存成功');
          this.refreshDetailCb(res);
          if (type === 'save') {
            this.$store.commit('ADD_LIST_REFRESH', this.$route.path.slice(0, this.$route.path.lastIndexOf('/')));
            this.$store.dispatch('delActiveViews');
          }
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 产品小类获取
    getPdsConfCategoryTree() {
      prodApi.getPdsConfCategoryTree().then(res => {
        this.productCategory = res.data;
      });
    },
    // 认证种类
    getCertSelect() {
      prodApi.certSelect().then(res => {
        this.$set(this.basicForm[6], 'options', res.data);
      });
    },
    // 获取字典选项
    getDict() {
      const codes = 'prod_file_sales_area';
      this.basicForm.forEach(value => {
        if (value.dictCode) {
          baseApi.getTypeValue(value.dictCode).then(res => {
            this.$set(value, 'options', res.data.rows);
          });
        }
      });
      baseApi.getTypesValue(codes).then(res => {
        this.countryList = res.data[codes];
        this.countryList.map(row => {
          row.salesAreaDv = row.value;
          return row;
        });
        this.$set(this, 'countryList', res.data[codes]);
      });
    },
    // 获取颜色
    getPdsConfColorTree(productCategoryId) {
      prodApi
        .getPdsConfAssetTree({
          type: '1',
          productCategoryId
        })
        .then(res => {
          this.$set(this, 'colorTreeList', res.data);
        });
    },
    // 是否是新增附件选项
    handleColorClick(data) {
      let isNew = true;
      // debugger
      this.detail.showColorsList.map(row => {
        if (row.assetId === data.id) {
          isNew = false;
        }
        // return row
      });
      if (isNew) {
        data.assetId = data.id;
        data.accessoryQuantity = 1;
        this.detail.showColorsList.push(data);
      }
    },
    // 删除特征或者附件
    deletItem(index, list) {
      list.splice(index, 1);
    },
    // 筛选颜色
    filterColor(value, data) {
      if (!value) return true;
      if (this.language === 'en') {
        return data.nameEn.indexOf(value) !== -1;
      } else {
        return data.nameCn.indexOf(value) !== -1;
      }
    }
  }
};
</script>
